const { PageContentInfo, PageContent, PageContentRequest, PageContentResponse } = require('./model')


const axios = require('axios')

const RUN_API_URL = 'http://showdoc.tengits.com:4999/server/?s=/api/item/updateByApi'

const RunApiTypeMap = {
  int: 'int',
  long: 'long',
  double: 'int',
  float: "int",
  byte: 'int',
  bool: 'boolean',
  string: "string"
}

async function updateByApi(data) {
  let params = {
    method: "post",
    url: RUN_API_URL,
    data
  }
  let res = await axios(params)
  return res
}


function genPageContent({ 
  interfaceItem = {},
   objMap = {}, 
   objDesMap = {},
   commonConfig={} ,
   pageConfig={}
  }={}) {
  const { fn, req, rsp, des } = interfaceItem
  let info = new PageContentInfo()
  info.description = des
  info.title = des
  info.url = `${commonConfig.base_url}${pageConfig.url}/${fn}`

  let request = new PageContentRequest()
  request.params.mode = "json"
  request.params.json = JSON.stringify(objMap[req],null,1)
  request.params.jsonDesc = genDescribe(objDesMap, req)

  let response = new PageContentResponse()
  response.responseExample = JSON.stringify(objMap[rsp],null,1)
  response.responseParamsDesc = genDescribe(objDesMap, rsp)


  const pageContent = new PageContent({ info, request, response })
  return pageContent
}

function getType(type) {
  let value = RunApiTypeMap[type]
  if (value) {
    return value
  }
  if (/^vector/.test(type)) {
    return "array"
  }
  return "object"
}

function genDescribe(objDesMap, key, pre = '') {
  let result = []
  let req = objDesMap[key]

  for (const k in req) {
    
    
    if (Object.hasOwnProperty.call(req, k)) {
      let item = req[k]
      result.push({
        name: pre + k,
        type: getType(item.type),
        require: item.require === "require" ? 1 : 0,
        value: "",
        remark: item.des
      })

      if (getType(item.type) === 'array') {
        let v  = item.type.match(/vector<(\w+)>/)
        let subDes
        if(RunApiTypeMap.hasOwnProperty(v[1])){
          subDes = {
            name: pre + item.key + "[number]",
            type: getType(v[1]),
            require: item.require === "require" ? 1 : 0,
            value: "",
            remark: item.des
          }
        }else{
          subDes = genDescribe(objDesMap, v[1], pre + item.key + '.')
        }
      
        result = result.concat(subDes)
      } else if (getType(item.type) === "object") {
        result = result.concat(genDescribe(objDesMap, item.type, pre + item.key + '.'))
      }
    }
  }
  return result
}


module.exports = {
  updateByApi,
  genPageContent
}